package cn.yoyo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginSuccess implements AuthenticationSuccessHandler {
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {

    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功 ....." + authentication);
        Object principal = authentication.getPrincipal();
        System.out.println("登录成功 .Authorities...." + authentication.getAuthorities());
        System.out.println("当前登录用户："+principal);
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        response.setStatus(200);
        Map<String, Object> map = new HashMap<>();
        map.put("status", 200);
        map.put("code", 0);
        map.put("msg", "登录成功");
        map.put("user",principal);
        for (GrantedAuthority authority : authorities) {
            if (authority.getAuthority().contains("G")) {
                map.put("action", "/");
            } else if (authority.getAuthority().contains("P")) {
                map.put("action", "/");
            } else {
                map.put("action", "/api/public/go2Login");
            }
        }
        out.write(objectMapper.writeValueAsString(map));
        out.flush();
        out.close();
    }
}
